package com.midian.common.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.midian.common.annotation.FunctionAnnotation;
import com.midian.common.annotation.FunctionAnnotationOverride;
import com.midian.common.annotation.FunctionAnnotationOverride.AnnotationOverride;
import com.midian.common.system.SysStatic;
import com.midian.model.user.vo.UserInfoVo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 * 
 * @Title:拦截器 
 * @Desription:权限拦截器
 * @Company:MDKG
 * @ClassName:PermissionInterceptor.java
 * @Author:zhucong
 * @CreateDate:2013-6-7 下午6:03:26  
 * @UpdateUser:zhucong  
 * @Version:0.1
 */
public class PermissionInterceptor extends MethodFilterInterceptor{
	
	private static final long serialVersionUID = 7150344259180460843L;

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		//获取注解信息
		Object action = invocation.getAction();
		String methodName = invocation.getProxy().getMethod();
		
		String funAuth = null; //目标被验证的权限
		Method method = action.getClass().getMethod(methodName);
		FunctionAnnotation annotation = method.getAnnotation(FunctionAnnotation.class);
		//如果Action方法上配置了权限验证，进行获取
		if (annotation != null) {
			funAuth = annotation.funAuth();
		}else{
		//如果Action方法上没有配置权限，从类那里获取
			//获取权限重写注释
			FunctionAnnotationOverride overrideAnnotation = action.getClass().getAnnotation(FunctionAnnotationOverride.class);
			if (overrideAnnotation != null) {
				//类级别的权限控制，如果是定义Action类权限，获取权限细项
				if(overrideAnnotation.isAction()){
					funAuth = overrideAnnotation.auth();
				}else{
				//如果不是定义Action类权限，获取Action方法的权限细项
					AnnotationOverride[] overrides = overrideAnnotation.value();
					for (AnnotationOverride annotationOverride : overrides) {
						if (annotationOverride.method().equals(methodName)) {
							funAuth = annotationOverride.funAuth();
							break;
						}
					}
				}
			}
		}
		if(funAuth!=null){
			UserInfoVo loginUser = (UserInfoVo) ActionContext.getContext().getSession().get(SysStatic.MC_LOGIN);
			if(!loginUser.checkFunAuth(funAuth)){
				return Action.NONE;
			}
		}
		
		String result = invocation.invoke();
		return result;
		//return invocation.invoke();
	}
}
